package com.ws.framework.util;

import java.net.URLDecoder;
import java.net.URLEncoder;

import javax.crypto.Mac;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

import com.ws.framework.ex.DigestException;

public class EncryptUtil {

    public static final String ENCODER_UTF8 = "UTF-8";

    public static final String ENCODER_ISO8859 = "ISO-8859-1";

    public static final String KEY_MAC = "HmacMD5";

    public static String encryptHMAC(String data, String key) {
		try {
			String keyStr = URLDecoder.decode(key, ENCODER_UTF8);
			byte[] keyRaw = keyStr.getBytes(ENCODER_ISO8859);
			SecretKey secretKey = new SecretKeySpec(keyRaw, KEY_MAC);
			Mac mac = Mac.getInstance(secretKey.getAlgorithm());
			mac.init(secretKey);
			byte[] raw = mac.doFinal(data.getBytes(ENCODER_UTF8));
			return URLEncoder.encode(new String(raw, ENCODER_ISO8859), ENCODER_UTF8);
		} catch (Exception e) {
			throw new DigestException(String.format("数据加密错误, data:'%s', key: '%s'", data, key), e);
		} 
    }
}